<template>
  <div>
    <local-loading :loading="loading"></local-loading>
    <page-header
      v-if="!loading"
      :title="experiment.name + '-' + title"
      :content="$t('studysubmit.Aufgabenbeschreibung')"
      class="PageHeader"
    />
    <page-main v-if="!loading">
      <el-descriptions
        :title="$t('studysubmit.Aufgabendetails')"
        :column="3"
        size="default"
        border
      >
        <el-descriptions-item span="3">
          <template #label>
            <div class="cell-item" style="width: 9rem">
              <svg-icon :icon-class="'sub_ms'" style="margin-right: 5px" />
              {{ $t("studysubmit.Aufgabenbeschrei") }}
            </div>
          </template>
          {{ experiment.remark ? experiment.remark : "无描述" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_fzjs'"
                style="margin-right: 5px; vertical-align: middle"
              />
              {{ $t("studysubmit.VerantwortungsbewussterLehrer") }}
            </div>
          </template>
          {{ experiment.leaderName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_cyjs'"
                style="margin-right: 5px; vertical-align: middle"
              />
              {{ $t("studysubmit.TeilnehmendeLehrer") }}
            </div>
          </template>
          {{
            experiment.assistants?.join(",")
              ? experiment.assistants?.join(",")
              : "无参与教师"
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_class'"
                style="
                  font-size: 18px;
                  margin-right: 5px;
                  vertical-align: middle;
                "
              />
              {{ $t("studysubmit.Klasse") }}
            </div>
          </template>
          {{ experiment.classes?.join(",") }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_task'"
                style="margin-right: 5px; vertical-align: middle"
              />
              {{ $t("studysubmit.Aufgabenname") }}
            </div>
          </template>
          {{ experiment.name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_start'"
                style="margin-right: 5px; vertical-align: middle"
              />
              {{ $t("studysubmit.Startzeit") }}
            </div>
          </template>
          {{ experiment.startTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_over'"
                style="
                  font-size: 18px;
                  margin-right: 5px;
                  vertical-align: middle;
                "
              />
              {{ $t("studysubmit.Kündigungszeit") }}
            </div>
          </template>
          {{ experiment.endTime }}
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions
        class="margin-top"
        :title="$t('studysubmit.Aufgabenanlage')"
        :column="1"
        size="default"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'sub_fj'"
                style="
                  font-size: 28px;
                  margin-right: 5px;
                  vertical-align: middle;
                "
              />
              {{ $t("studysubmit.Anhangsinformationen") }}
            </div>
          </template>
          <span v-if="files.length === 0">
            <svg-icon :icon-class="'nofd'" style="width: 100%; height: 100%" />
          </span>
          <div
            v-for="(file, index) in files"
            :key="index"
            style="
              height: 60px;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <span v-throttle="() => fileClick(file)" class="file_item">
              <svg-icon
                :icon-class="file.name.split('.').at(-1)"
                style="
                  font-size: 28px;
                  margin-right: 5px;
                  vertical-align: middle;
                "
              />
              {{ file.name }}
            </span>

            <span>
              <el-tooltip content="查看" placement="bottom" effect="light">
                <svg-icon
                  v-throttle="() => fileClick(file)"
                  :icon-class="'fd_view'"
                  class="operation_class"
                  style="
                    font-size: 18px;
                    line-height: 18px;
                    vertical-align: middle;
                    color: var(--el-menu-active-color);
                    cursor: pointer;
                  "
                />
              </el-tooltip>
              <el-tooltip content="下载" placement="bottom" effect="light">
                <svg-icon
                  v-throttle="() => handleDownload(file)"
                  :icon-class="'fd_download'"
                  style="
                    margin-left: 14px;
                    font-size: 18px;
                    line-height: 18px;
                    vertical-align: middle;
                    color: var(--el-menu-active-color);
                    cursor: pointer;
                  "
                  class="operation_class"
                />
              </el-tooltip>
            </span>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        :title="$t('studysubmit.Überprüfungsinformationen')"
        :column="4"
        size="default"
        class="margin-top"
        border
        v-if="experiment.fileStatus == 2"
      >
        <el-descriptions-item width="100px">
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'fenshu'"
                style="
                  margin-right: 5px;
                  font-size: 20px;
                  vertical-align: middle;
                "
              />
              {{ $t("studysubmit.Bruch") }}
            </div>
          </template>
          {{ experiment.grade ? experiment.grade : "无" }}
        </el-descriptions-item>
        <el-descriptions-item width="100px">
          <template #label>
            <div class="cell-item">
              <svg-icon
                :icon-class="'pingyu'"
                style="
                  margin-right: 5px;
                  font-size: 20px;
                  vertical-align: middle;
                "
              />
              {{ $t("studysubmit.Kommentar") }}
            </div>
          </template>
          {{ experiment.comment ? experiment.comment : "无" }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        class="margin-top"
        :title="$t('studysubmit.Aufgabeneingabe')"
        :column="1"
        size="default"
        border
      />
      <div style="width: 80%">
        <file-upload
          :files="fileLists"
          :disabled="!disabled"
          @on-success="handleSuccess"
          @on-change="handleChange"
          @on-remove="handleRemove"
          :progress-flag="progressFlag"
          :load-progress="loadProgress"
        ></file-upload>
      </div>
      <div class="btnlink">
        <el-button v-if="!disabled" v-throttle="submit" type="" size="large">
          <svg-icon
            :icon-class="
              title == '修改' ? 'xiugai' : title == '查看' ? 'chakan' : 'tijiao'
            "
            style="margin-right: 5px; font-size: 24px"
          />
          {{
            title == "修改"
              ? $t("studysubmit.modifizieren")
              : title == "提交"
              ? $t("studysubmit.Absenden")
              : $t("studysubmit.Prüfung")
          }}
        </el-button>
        <el-button size="large" @click="cancel">
          <svg-icon
            :icon-class="'fd_cancel_l'"
            style="margin-right: 5px; font-size: 24px"
          />
          {{ $t("studysubmit.Abbrechen") }}
        </el-button>
      </div>
    </page-main>
    <el-dialog
      v-model="imgVisible"
      append-to-body
      title="预览"
      style="width: 60%"
      @close="false"
    >
      <iframe :src="previewURL" style="width: 100%; height: 500px"></iframe>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Studysubmit",
  inheritAttrs: false,
});
// 导入引用
import FileUpload from "@/components/FileUpload/index.vue";
import { useRoute } from "vue-router";
import { UploadRawFile } from "element-plus";
import { detailSubmitTask, detailTask, verifyExpSubmit } from "@/api/task";
import { DetailTaskDataRequest } from "@/api/task/types";
import { downloadFile, uploadExpAnnex } from "@/api/file";
import { downloadBlob, verifyFile } from "@/utils/file";
import { stringToBase64 } from "@/utils/btoa";
import SparkMD5 from "spark-md5";
import router from "@/router";
import { submitExp } from "@/api/submit";

const loading = ref(false);
const route = useRoute();
const imgVisible = ref(false);
const disabled = ref(false);
// 文件id
const filesId = ref([]);
const previewURL = ref("");
const title = ref("");

const experimentId = ref();
const experiment = ref<DetailTaskDataRequest>({});
// 文件
const files = ref<UploadRawFile[]>([]);
const fileLists = ref<UploadRawFile[]>([]);
const loadProgress = ref(0);
const progressFlag = ref(false);

// 查询函数
const handleQuery = () => {
  experimentId.value = Number(route.query.experimentId);
  loading.value = true;
  // 查看任务信息
  detailSubmitTask(experimentId.value)
    .then(({ data }) => {
      files.value = [];
      data.fileList?.forEach((item: any) => {
        let file: any = {
          name: "",
          url: "",
          id: 0,
          path: "",
        };
        file.name = item.name;
        file.url = item.url;
        file.id = item.id;
        file.path = item.path;
        files.value.push(file);
      });

      data.expList?.forEach((item: any) => {
        let file: any = {
          name: "",
          url: "",
          id: 0,
          path: "",
        };
        file.name = item.name;
        file.url = item.url;
        file.id = item.id;
        file.path = item.path;
        fileLists.value.push(file);
        filesId.value.push(file.id as never);
      });

      experiment.value = data;

      disabled.value =
        data.status == 0
          ? data.fileStatus === 1
            ? false
            : data.fileStatus === 2
            ? true
            : data.fileStatus === 3
            ? false
            : false
          : data.fileStatus === 3
          ? false
          : true;
      title.value =
        data.status == 0
          ? data.fileStatus === 1
            ? "修改"
            : data.fileStatus === 2
            ? "查看"
            : data.fileStatus === 3
            ? "重新提交"
            : "提交"
          : data.fileStatus === 3
          ? "重新提交"
          : "查看";
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      loading.value = false;
    });
};

function handleSuccess(res: any, file: any, fileList: any) {
  if (res.error === "") {
    console.log("成功");
  } else {
  }
}

function cancel() {
  router.push({
    path: "/studyinfo/studytask",
    query: {
      courseId: route.query.courseId,
    },
  });
}

function submit() {
  const fileIds = filesId.value.join(",");
  if (!fileIds) {
    ElMessage.warning("请上传文件");
    return;
  }

  ElMessageBox.confirm("确认提交报告?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    loading.value = true;
    submitExp(fileIds, experimentId.value)
      .then(() => {
        ElMessage.success("提交成功");

        router.push("/studyinfo/studytask");
        loading.value = false;
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

function handleChange(file: any, fileList: any) {
  // 文件上传前的操作
  if (!verifyFile(file, fileList)) return;
  file.status = "uploading";
  setTimeout(() => {
    loadProgress.value = 5;
  }, 100); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 10;
  }, 200); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 30;
  }, 300); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 50;
  }, 400); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 70;
  }, 500); // 一秒后关闭进度条
  setTimeout(() => {
    loadProgress.value = 80;
  }, 600); // 一秒后关闭进度条
  const reader = new FileReader();
  const spark = new SparkMD5.ArrayBuffer();
  reader.readAsArrayBuffer(file.raw);
  reader.onload = (e) => {
    spark.append(reader.result as ArrayBuffer);
    const md5 = spark.end();
    uploadExpAnnex(file.raw, md5, Number(route.query.experimentId))
      .then((res) => {
        loadProgress.value = 100;
        file.path = res.data.path;
        file.url = res.data.url;
        filesId.value.push(res.data.id as never);
        fileLists.value.push(file.raw);
        setTimeout(() => {
          progressFlag.value = false;
          loadProgress.value = 0;
          file.status = "success";
          ElMessage.success("文件上传成功");
        }, 1000); // 一秒后关闭进度条
      })
      .catch(() => {
        const index = fileList.indexOf(file);
        fileList.splice(index, 1);
        ElMessage.error("文件上传失败");
      });
  };
}

// 点击移出文件 并且将文件列表进行重新摆列
function handleRemove(file: any, fileList: any) {
  ElMessageBox.confirm("确认删除此文件?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    fileLists.value = fileList.filter((item: any) => {
      return item.uid != file.uid;
    });

    // 过滤id
    filesId.value = filesId.value.filter((item: any) => {
      return item != file.id;
    });
  });
}

// 下载文件
function handleDownload(row?: any) {
  downloadFile(row.path, row.name).then((response) => {
    downloadBlob(response);
  });
}

function fileClick(row: any) {
  const fileName = row.name.split(".");
  const fileExt = fileName.at(-1) ?? "";

  if (fileExt == "pdf") {
    previewURL.value = "http://oss.dachtech.info/" + row.path;
  } else {
    const str = stringToBase64(row.url);
    previewURL.value = `http://1.116.4.57:8012/onlinePreview?url=${str}`;
  }
  imgVisible.value = true;
}

onMounted(() => {
  if (route.query.experimentId) {
    verifyExpSubmit(
      route.query.experimentId as unknown as number,
      route.query.courseId as unknown as number
    )
      .then(() => {
        handleQuery();
      })
      .catch((e) => {
        router.push({
          path: "/studyinfo/studytask",
          query: {
            courseId: route.query.courseId,
          },
        });
      });
  } else {
    router.push({
      path: "/studyinfo/studytask",
      query: {
        courseId: route.query.courseId,
      },
    });
  }
});
</script>

<style scoped>
.PageHeader {
  border-left: 1px solid var(--el-bg-color);
  border-bottom: 1px solid var(--el-bg-color);
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}

.file_item:hover {
  color: var(--el-menu-active-color);
  cursor: pointer;
}

.btnlink {
  margin: 0 auto;
  text-align: center;
}
</style>
